<template>
  <div :id="id" />
</template>

<script setup>
import { ref, watchEffect, onMounted, onUnmounted } from 'vue'
import Player, { Events } from 'xgplayer'
import HlsJsPlugin from 'xgplayer-hls.js'
import 'xgplayer/dist/index.min.css'
import { guid } from '@/utils'

defineOptions({
  name: 'VideoPlayer'
})

const id = 'video-player-' + guid(8, true)

const emits = defineEmits(['play', 'pause', 'end', 'error'])

const props = defineProps({
  url: {
    type: String,
    default: ''
  },
  startTime: {
    type: Number,
    default: 0
  },
  poster: {
    type: String,
    default: ''
  },
  autoplay: {
    type: Boolean,
    default: true
  },
  loop: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'video',
    validator(value) {
      const type = new Set(['video', 'hls'])
      return type.has(value)
    }
  },
  screenShot: {
    type: Boolean,
    default: false
  }
})

const player = ref(null)

const playerConfig = ref({
  id,
  url: props.url,
  poster: props.poster,
  lang: "zh-cn", //设置中文
  //自动播放
  autoplayMuted: true,
  autoplay: props.autoplay,
  //循环播放
  loop: props.loop,
  screenShot: props.screenShot,
  /**画中画 */
  pip: true,
  pipConfig: {
    bottom: 100,
    right: 100,
    width: 320,
    height: 180,
  },
  isLive: false,
  videoInit: true,
  volume: 1, //音量 0 -  1
  startTime: props.startTime, //视频起播时间（单位：秒）
  lastPlayTimeHideDelay: 5, //提示文字展示时长（单位：秒）
  // 倍数播放
  playbackRate: [0.5, 0.75, 1, 1.5, 2],
  defaultPlaybackRate: 1,
  rotateFullscreen: true,
  videoAttributes: {
    crossOrigin: 'anonymous'
  },
  plugins: []
})

function initPlayer() {
  if(player.value) return
  if(props.type === 'hls') {
    playerConfig.value.hls = {
      retryCount: 3, // 重试 3 次，默认值
      retryDelay: 1000, // 每次重试间隔 1 秒，默认值
      loadTimeout: 10000, // 请求超时时间为 10 秒，默认值
      fetchOptions: {
        // 该参数会透传给 fetch，默认值为 undefined
        mode: 'cors'
      }
    }
    playerConfig.value.plugins.push(HlsJsPlugin)
  }
  player.value = new Player(playerConfig.value)
  player.value.on(Events.PLAY, $event  => {
    emits('play', $event )
  })
  player.value.on(Events.PAUSE, $event => {
    emits('pause', $event )
  })
  player.value.on(Events.ENDED, $event => {
    emits('end', $event )
  })
  player.value.on(Events.ERROR, error => {
    console.log(error)
    emits('error', error)
  })
}

function isAppleDevice() {
  const ua = navigator.userAgent.toLowerCase()
  return /iphone|ipad|phone|Mac/i.test(ua)
}

function play() {
  player.value?.play()
}

function pause() {
  player.value?.pause()
}

function replay() {
  player.value?.replay()
}

function reload() {
  player.value?.reload()
}

onMounted(() => {
  watchEffect(() => {
    if(!player.value) {
      playerConfig.value.startTime = props.startTime
      playerConfig.value.url = props.url
      initPlayer()
      console.log( player.value, '255')
    } else {
      player.value.src = props.url
      player.value.poster = props.poster
      player.value.currentTime = props.startTime
    }
  })
})

onUnmounted(() => {
  player.value?.destroy()
  player.value = null
})

defineExpose({
  play,
  pause,
  reload,
  replay,
  player: player.value
})
</script>

<style scoped lang="scss">
#video-player {
  width: 320px;
  height: 180px;
}
</style>